/**
 *
 */
package com.honeybees.framework.spring.mvc.filter;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.honeybees.framework.common.util.HTTPUtils;


/**
 * <dl>
 * <dt><b> 清除 跨站脚本攻击（XSS）的Request </b></dt>
 * <p>
 * <dd>功能描述</dd>
 * </dl>
 * <p>
 * Copyright (C) All rights reserved.
 * </p>
 *
 * @author 李远明
 * @since 2017-03-08 20:02:55 新建
 */
public class XSSRequestWrapper extends HttpServletRequestWrapper {

    /**
     * @param request 当前请求
     */
    public XSSRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    /**
     * {@inheritDoc}
     *
     * @author 李远明
     * @version 2017-03-08 20:04:01
     */
    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values == null) {
            return null;
        }
        int c = values.length;
        String[] encodedValues = new String[c];
        for (int i = 0; i < c; i++) {
            String encodedValue = HTTPUtils.trimXss(values[i]);
            encodedValues[i] = encodedValue;
        }
        return encodedValues;
    }

    /**
     * {@inheritDoc}
     *
     * @author 李远明
     * @version 2017-03-08 20:09:48
     * @see HttpGetMethodRequestWrapper#getParameter(String)
     */
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        String secVal = HTTPUtils.trimXss(value);
        return secVal == null ? null : convert(secVal);
    }

    /**
     * @param value
     * @return
     * @author 李远明
     * @version 2017-03-08 20:16:10
     */
    private String convert(String value) {
        value = value.trim();
        try {
            return new String(value.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return value;
        }
    }

    /**
     * {@inheritDoc}
     *
     * @author 李远明
     * @version 2017-03-08 20:11:27
     */
    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        return HTTPUtils.trimXss(value);
    }

}
